const BARREL_SIZE= 5;

import {
  sortInsert
} from './sortInsert';

export const sortBarrel = (array: number[], barrelSize = BARREL_SIZE) => {
  let minValue = array[0];
  let maxValue = array[0];

  for (let v of array) {
    if (v < minValue) {
      minValue = v;
    }
    if (v > maxValue) {
      maxValue = v;
    }
  }

  const barrelCount = Math.ceil((maxValue - minValue) / barrelSize);
  const barrels: number[][] = [];

  for (let i = 0; i < barrelCount; i++) {
    barrels.push([]);
  }

  for (let v of array) {
    const barrelIndex = Math.floor((v - minValue) / barrelSize);
    barrels[barrelIndex].push(v);
  }

  let arrSort: number[] = [];
  
  for (let v of barrels) {
    if (v.length) {
      let arrSI = sortInsert(v);
      arrSort = arrSort.concat(arrSI);
    }
  }

  return arrSort;
};
